<?php
/**
 * @filename source_module.php 2013-11-11 02:10:56x
 * @author Huming Xu <huming17@126.com>
 * @version 1.0.0
 * @copyright DZF (c) 2013, Huming Xu
 */
class ctrl_user_detail extends user_detail {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }
    
    public function __construct() {
        $this->_table   = 'user_detail';
        $this->_pk      = 'user_id';
        $this->_keyword = 'user_realname';
        parent::__construct();
    }
    /*
     * 	取出一条信息
     */
    public function do_detail($id = '') {
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $detail = array();
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $user = $this->one_info('user', 'user_id', $id);
        $detail = $this->one_info($this->_table, $this->_pk, $id);
        $detail['user_name'] = $user['user_name'];
        //DEBUG 输出
        $return['code']="0";
        $return['data']=$detail;
        if($_G['api']){
            //DEBUG 接口输出
            echo format_data($return, $_G['api'], $_G['mod'], $_G['action'], $_G['do'],'pc','msg_admin','admin');
        }else{
            //DEBUG 模板输出
            include template($_G['mod'].'/'.$_G['action'].'/'.$_G['do']);
        }
    }

    /*
    * 导出用户的用户名 
    */
    public function do_usernameexport(){
        global $_G;
        //此处接收传递的搜索条件
        $sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校编号sm_id
        $class_id = isset($_REQUEST['class_id']) && !empty($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//班级编号class_id
        
        if($sm_id){
            $whereSql.= " and ud.sm_id = ".$sm_id." ";
        }
        
        if($class_id){
            $whereSql.= " and ud.class_id = ".$class_id." ";
        }
        
        $sql = "select u.user_name, ud.user_realname from ".DB::table('user')." as u "
                . " left join ".DB::table('user_detail')." as ud on ud.user_id = u.user_id where 1 = 1 ".$whereSql;
        
        $sql_result = DB::fetch_all($sql);
        
        $filename = 'yhmdc'.date('YmdHis').'.xls'; //设置文件名
        
        $titles = ['姓名', '用户名'];
        
        $data = [];
        
        //将上述结果集转换为目标数组
        if(!empty($sql_result) && is_array($sql_result)){
            foreach ($sql_result as $k => $item) {
                $data[$k] = [
                    0 => isset($item['user_realname']) ? $item['user_realname'] : '',
                    1 => isset($item['user_name']) ? $item['user_name'] : ''
                ];
            }
        }
        
        $xlsData = makeXls($titles, $data);
        
        $target = SITE_ROOT.'data/upload/';
        
        $fp = fopen($target.$filename, 'w');
        //向目标文件写入操作
        fwrite($fp, $xlsData);

        fclose($fp);
        
        $return['code'] = '1';
        //检测是否对应已生成csv文件
        if(is_file($target.$filename)){
            
            //2017-6-6 11:51:34 此处将该csv文件上传到文件服务器，同时删除本地的文件
            $data = ['filedata'  =>  new CURLFile($target.$filename), 'dir' => '/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $res = curl_exec($ch);
            curl_close($ch);

            //此处删除掉本地的文件
            @unlink($target.$filename);

            if($res == 'success'){//成功
               $return['code'] = '0';
               $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/'.$filename;
            }
            else{//远程文件上传失败
               $return['code'] = '1';
               $return['data']= [];
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     *  添加系统信息
    */
    public function do_add() {
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $return['code'] = '1';
        $request_data = isset($_REQUEST[$this->_table]) && !empty($_REQUEST[$this->_table]) ? $_REQUEST[$this->_table] : '';
        if ($request_data) {
            $data=$request_data;//TODO 和数据库字段数组求差集 以便过滤冗余数据 避免SQL插入不匹配问题
            $insert_id = $this->add($this->_table, $data);
            if ($insert_id) {
                $return['code'] = '0';
                $return['data']['id'] = (string)$data['user_id'];
                if($_G['api']){
                    echo format_data($return, $_G['api'], $_G['mod'], $_G['action'], $_G['do'],'pc','msg_admin','admin');die;
                }else{
                    showmessage('操作成功','index.php?mod='.$_G['mod'].'&action='.$_G['action'].'&do=index');
                }
            }
        }else{
            include template($_G['mod'].'/'.$_G['action'].'/'.$_G['do']);
        }
    }

    /*
     *  编辑系统信息
     */

    public function do_edit() {
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $return['code'] = '1';
        $request_data = isset($_REQUEST[$this->_table]) && !empty($_REQUEST[$this->_table]) ? $_REQUEST[$this->_table] : '';
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        if ($request_data && $id) {
            $data=$request_data;//TODO 和数据库字段数组求差集 以便过滤冗余数据 避免SQL插入不匹配问题
            $where = array($this->_pk => $id);
            $effect_row = $this->edit($this->_table, $data, $where);
            if ($effect_row) {
                $return['code'] = '0';
                if($_G['api']){
                    echo format_data($return, $_G['api'], $_G['mod'], $_G['action'], $_G['do'],'pc','msg_admin','admin');die;
                }else{
                    showmessage('操作成功','index.php?mod='.$_G['mod'].'&action='.$_G['action'].'&do=index');
                }
            }
        }else{
            include template($_G['mod'].'/'.$_G['action'].'/'.$_G['do']);
        }        
    }

    /*
     *  删除系统信息
    */
    public function do_delete() {
        global $_G;
        //ini_set("display_errors","On");
        //error_reporting(E_ALL);
        $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
        $return['code'] = '1';
        if ($id) {
            $where = array($this->_pk => $id);
            $effect_row = $this->delete($this->_table, $where, $limit = 1);
            if ($effect_row) {
                $return['code'] = '0';
            }
        }
        if($_G['api']){
            //DEBUG 接口输出
            echo format_data($return, $_G['api'], $_G['mod'], $_G['action'], $_G['do'],'pc','msg_admin','admin');
        }else{
            //DEBUG 模板输出
            showmessage('操作成功','index.php?mod='.$_G['mod'].'&action='.$_G['action'].'&do=index');
        }
    }

    /*
     *  系统信息列表
     */

    public function do_index() {
        global $_G;
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start = (($page - 1) * $perpage);
        $wheresql = "";
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        if ($keyword) {
            $wheresql = " AND ".$this->_keyword." LIKE '%" . $keyword . "%' ";
        }
        $orderby = " ORDER BY ".$this->_pk." DESC ";
        //DEBUG 初始化请求请求获取一页列表数据的参数
        $page_condition = array(
            'page' => $page, //int 请求页面 页码
            'limit' => $limit, //int 每页请求个数
            'perpage' => $perpage, //int 每页显示个数
            'wheresql' => $wheresql, //string //条件SQL语句 
            'orderby' => $orderby, //string 排序规则
        );
        //DEBUG 列表数据返回结构
        /*
          $page_result = array(
          //int 返回结果总数
          'total_rows' => $total_rows,
          //array 一页数据数组
          'page_data' => $page_data
          );
         */
        $page_result = $this->index($this->_table, $page_condition);        
        if ($_G['api']) {
            $return['code'] = '0';
            $return['data'] = $page_result;
            echo format_data($return, $_G['api'], $_G['mod'], $_G['action'], $_G['do'],'pc','msg_admin','admin');
        } else {
            $multipage = multi($page_result['total_rows'], $perpage, $page, "index.php?mod=".$_G['mod']."&action=".$_G['action']."&do=".$_G['do']."&keyword=".$keyword);//TODO 路由方法优化
            include template($_G['mod'].'/'.$_G['action'].'/'.$_G['do']);
        }
    }
    
    //根据用户获取学校id
    public function do_get_smid(){
    	global $_G;
    	$sm_id =[];
    	if($_G['user_id']){
    		$sm_id[sm_id] = $this->one_sm_info('user_detail', 'user_id', $_G['user_id']);
    	}
    	if($sm_id){
    		$return['code'] = '0';
    		$return['data'] = $sm_id;
    	}else{
    		$return['code'] = '1';
    		$return['data'] = [];
    	}
    	echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
    	return false;
    }
}

?>